package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

/**
 * @Author Andy
 * @Description //TODO LoginCheckerFilter
 * @Date 2021/10/27 12:15 上午
 * @Version 1.0
 **/
@WebFilter
public class LoginCheckerFilter implements Filter {
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        String requestUri = httpServletRequest.getRequestURI();
        String[] urlArray = {
            "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/loginout"
        };


        if (Arrays.stream(urlArray).anyMatch(url-> ANT_PATH_MATCHER.match(url, requestUri))){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            if (!Objects.isNull(httpServletRequest.getSession().getAttribute("employee"))){
                filterChain.doFilter(servletRequest, servletResponse);
            }else {
                httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            }
        }

    }
}
